<?php
require_once APPLICATION_PATH . '/controllers/LoginController.php';

/**
 * 消息控制器
 * @author Administrator
 *
 */
class MsgController extends LoginController
{

    public function init()
    {
        parent::init();
    }

    /**
     * 列表
     * @see LoginController::indexAction()
     */
    public function indexAction()
    {
        if($this->getRequest()->isPost()){
        	//获取数据
        	$whereToUsers = Application_Model_Msg::TO_ALL . "," .$this->_user_id;
        	if($this->_user->type == 0){
        		$whereToUsers .= "," . Application_Model_Msg::TO_ADMIN;
        		$whereToUsers .= "," . Application_Model_Msg::TO_SYS;
        	}
        	$where = " `to_user` IN ({$whereToUsers}) ";
        	$type = $this->getRequest()->getParam("type",NULL);
        	$typeid = intval($type);        	
        	if($type !== NULL){
        		$where .= " AND (`type` = {$typeid}) ";
        	}
        	
        	$userM = new Application_Model_DbTable_Msg();
        	$pageM = $this->_helper->Flexgp();
			$data = $userM->jqfetchAll($pageM,$where,"id DESC");
			foreach ($data["data"] as &$d){
				$d["type"] 			= !empty(Application_Model_Msg::$TYPE_ARR[$d["type"]])?Application_Model_Msg::$TYPE_ARR[$d["type"]] : $d["type"];
				$d["from_user"] 	= !empty(Application_Model_Msg::$FROM_ARR[$d["from_user"]])?Application_Model_Msg::$FROM_ARR[$d["from_user"]] : $d["from_user"];				
				$d["to_user"] 		= !empty(Application_Model_Msg::$TO_ARR[$d["to_user"]])?Application_Model_Msg::$TO_ARR[$d["to_user"]] : $d["to_user"];
				$d["create_time"] 	= date("Y-m-d H:i:s",$d["create_time"]);
			}
			$data = $this->view->jqflexgrid($data,"id");
		    $this->_helper->json($data); 
        }else{
        	//获取页面
    		$this->view->title = "消息及提醒列表";
        }
    }

    /**
     * 添加信息
     * @param Application_Form_Base $formM
     * @param array $data 来自request的数据
     * @return array $resdata;
     */
    private function add(Application_Form_Base $formM,$data)
    {
    	//提交数据
        //json返回的数据
        $reData = array(
        	"status" => 0,
        	"msg"	 => "失败。"
        );
        //$data = $this->getRequest()->getParams();
        if($formM->isValid($data)){
        	$userM = new Application_Model_DbTable_msg();
        	$data  = $formM->getValues(); 
        	//$data["id"] = $data["userid"];unset($data["userid"]);
        	//$data['create_user'] = $this->_user_id;   //创建人id
	       	$data['create_time'] = time();                           //创建时间
	       	try {
		       	$result = $userM->insert($data);
		       	$reData["status"]=1;
		       	$reData["msg"]="成功！";
	       	}catch (Exception $e){
        		$reData["form"] = $formM->render();
	       		$reData["msg"]="数据库错误！" . $e->getMessage();
	       	}
        }else{
        	$reData["msg"]="表单填写有误！";
        	$reData["form"] = $formM->render();
        }
        
        return $reData;
    }
    

    /**
     * 添加
     * @see LoginController::indexAction()
     */    
	public function addAction()
    {
    	$formM = new Application_Form_Base("msg");
    	if($this->getRequest()->isPost()){
    		$data = $this->getRequest()->getParams();
        	$reData = $this->add($formM,$data);
        	$this->_helper->json($reData);
        }else{
        	//获取表单
    		$this->view->form = $formM;
        }
        $this->_helper->layout()->disableLayout();
        $this->renderScript("zendform.phtml");
    }    
    
    /**
     * 添加客户提醒日程安排
     * @see LoginController::indexAction()
     */    
	public function addalarmAction()
    {
    	$customer = intval($this->getRequest()->getParam("customer"));
    	$formM = new Application_Form_Base("msg");
    	$formM->setAction($this->view->pagePath . "/msg/addalarm");
    	foreach ($formM as $e){
    		$eName = $e->getName();
    		switch ($eName){
    			case "from_user":
		    		$formM->hideElement($e);
		    		$e->setValue("".Application_Model_Msg::FROM_SYS);
		    		break;
    			case "to_user":
		    		$formM->hideElement($e);
		    		$e->setValue($this->_user_id);
    				break;
    			case "type":    				
		    		$formM->hideElement($e);
		    		$e->setValue(Application_Model_Msg::TYPE_ALARM);
    				break;
    			case "foreign_key":
		    		$formM->hideElement($e);
		    		$e->setValue("customer");
    				break;
    			case "foreign_value":    				
		    		$formM->hideElement($e);
		    		$e->setValue($customer);				
    				break;
    			case "msg":    				
		    		$e->setlabel("提醒内容");				
    				break;
    			default:
    				break;
    		}
    	}
    	
    	if($this->getRequest()->isPost()){
    		$data = $this->getRequest()->getParams();
    		$data["alarm_time"] = empty($data["alarm_time"])?NULL:strtotime($data["alarm_time"]);
        	$reData = $this->add($formM,$data);
        	$this->_helper->json($reData);
        }else{
        	//获取表单
    		$this->view->form = $formM;
        }
        $this->_helper->layout()->disableLayout();
        $this->renderScript("zendform.phtml");
    }   
    
    /**
     * 编辑
     * @see LoginController::indexAction()
     */
    public function editAction()
    {
    	$id = intval($this->getRequest()->getParam("id",0));
    	$formM = new Application_Form_Base("msg");
    	$userM = new Application_Model_DbTable_Msg();
        $formM->setAction("msg/edit");
    	
    	if($this->getRequest()->isPost()){
        	//提交数据
        	$reData = array(
        		"status" => 0,
        		"msg"	 => "失败。"
        	);
        	$data = $this->getRequest()->getParams();
        	if($formM->isValid($data)){
        		
        		$data  = $formM->getValues(); 
        		unset($data["userid"]);
	        	try {
		        	$result = $userM->update($data, " `id` = {$id} ");
		        	$reData["status"]=1;
		        	$reData["msg"]="成功！";
		        	Application_Service_Msg::write(
		        		"{$this->_user_name}修改客户：{$data["name"]}",
		        		Application_Model_Msg::TYPE_USERDO_LOG
		        	);
	        	}catch (Exception $e){
        			$reData["form"] = $formM->render();
	        		$reData["msg"]="数据库错误！" . $e->getMessage();
	        	}
        	}else{
        		$reData["msg"]="表单填写有误！";
        		$reData["form"] = $formM->render();
        	}
        	$this->_helper->json($reData);
        }else{
        	//获取表单
        	$data = $userM->fetchRow(" `id` = {$id} ");
        	if($data){
        		$formM->setDefaults($data->toArray());
        	}
    		$this->view->form = $formM;
        }
        $this->_helper->layout()->disableLayout();
        $this->renderScript("zendform.phtml");
    }
    
	/**
	 * 删除
	 */
	public function delAction()
	{
		$reData = array(
			"status" => 0,
			"msg"    => "参数错误"
		);	    
    	$id = (array)$this->getRequest()->getParam('id');
    	if($id){
			$userM = new Application_Model_DbTable_Msg();
			$where = $userM->getAdapter()->quoteInto('`id` IN(?)', $id);
    		if($result = $result = $userM->delete($where)){
    			$reData = array(
					"status" => 1,
    		 		"msg"    => "成功删除{$result}条数据！"
    		 	);
    		 	$id = implode(",",$id);
    		 	Application_Service_Msg::write(
	        		"{$this->_user_name} 删除客户：{$id}",
	        		Application_Model_Msg::TYPE_USERDO_LOG
	        	);
    		 }
	    }else{
	        	
	    }
	    $this->_helper->json($reData);
   }

	/**
	 * 显示操作日志
	 */  
	public function listlogAction(){
		$msgM = new Application_Model_DbTable_Msg();
		$redata = $msgM->getListByType(Application_Model_Msg::TYPE_USERDO_LOG,20);
		$this->_helper->json($redata);
	}
	
	/**
	 * 显示站内信
	 */  
	public function listmsgAction(){
		$msgM = new Application_Model_DbTable_Msg();
		$redata = $msgM->getListByType(Application_Model_Msg::TYPE_MSG,20,$this->_user_id);
		$this->_helper->json($redata);
	}

	/**
	 * 显示日程安排
	 */  
	public function listdalyAction(){
		$msgM = new Application_Model_DbTable_Msg();
		$redata = $msgM->getListByType(Application_Model_Msg::TYPE_ALARM,20,$this->_user_id);
		$this->_helper->json($redata);
	}

	/**
	 * 显示某客户提醒
	 */  
	public function listbycustomerAction(){
		$customer = intval($this->getRequest()->getParam("customer")); 	//客户id
		$limit    = intval($this->getRequest()->getParam("limt"));		//提取数量
		$timemin  = $this->getRequest()->getParam("timemin");			//时间限制
		$timemax  = $this->getRequest()->getParam("timemax");			//时间限制		
		$userid   = intval($this->getRequest()->getParam("user",$this->_user_id)); 	//业务员id
		
		
		//转换日期
		$timemin  = $timemin?strtotime($timemin):$timemin;
		$timemax  = $timemax?strtotime($timemax):$timemax;
		$timeLmt  = !empty($timemin)&&!empty($timemax) ? array($timemin,$timemax): NULL;
		
		$msgM = new Application_Model_DbTable_Msg();
		$redata = $msgM->getAlarmByCustomer($customer,$limit,$timeLmt,$userid);
		$userM  = new Application_Model_DbTable_User();	    	
    	$userKV = $userM->getKVnameid();
		foreach ($redata as &$d){
			$d["create_time"] 	= date("Y-m-d H:i:s",$d["create_time"]);
			$d["alarm_time"] 	= !empty($d["alarm_time"])?date("Y-m-d",$d["alarm_time"]):"";			
			$d["from_user"] 	= !empty($userKV[$d["from_user"]])?$userKV[$d["from_user"]]:"";			
			$d["to_user"] 		= !empty($userKV[$d["to_user"]])?$userKV[$d["to_user"]]:"";			
		}
		
		$this->_helper->json($redata);
	}
	
	/**
	 * 显示某客户提醒 返回登陆者负责的 昨天、今天、明天、以前所有未处理
	 */  
	public function listbycustomeranddaliyAction(){
		$customer = intval($this->getRequest()->getParam("customer")); 	//客户id
		/*$limit    = intval($this->getRequest()->getParam("limt"));		//提取数量
		$timemin  = $this->getRequest()->getParam("timemin");			//时间限制
		$timemax  = $this->getRequest()->getParam("timemax");			//时间限制		
		$userid   = intval($this->getRequest()->getParam("user",$this->_user_id)); 	//业务员id*/
		
		//转换日期
		$timemin  = 0;
		$timemax  = strtotime("+1 day");
		$timeLmt  =  array($timemin,$timemax);
		
		$msgM = new Application_Model_DbTable_Msg();
		$redata = $msgM->getAlarmByCustomer($customer,10000,$timeLmt,$this->_user_id);

    	$data = array(
    		"today"		=>array(),
    		"tomorrow"	=>array(),
    		"yestoday"	=>array(),
    		"before"	=>array()
    	);
    	$todayO = strtotime(date("Y-m-d 00:00:00",time()));
		foreach($redata as $k => &$d){
						
			$d["create_time_f"] = date("Y-m-d H:i:s",$d["create_time"]);
			$d["alarm_time_f"] 	= date("Y-m-d",$d["alarm_time"]);	
						
			if($d["alarm_time"] >= ($todayO+3600*24)){
				$data["tomorrow"][] = $d;
			}else if ($d["alarm_time"] >= ($todayO)){
				$data["today"][] = $d;
			}else if($d["alarm_time"] > ($todayO-3600*24)){
				$data["yestoday"][] = $d;
			}else{
				if($d["state"] == 1){
					unset($redata[$k]);
					continue;
				}
				$data["before"][] = $d;				
			}
			
		}
		
		$this->_helper->json($data);
	}
	
	/**
	 * 切换读取状态
	 */
	public function togglestateAction()
	{
		$id = intval($this->getRequest()->getParam("id"));
		//$state = $this->getRequest()->getParam("state");
		$redata = array(
			"status" => 0,
			"msg"	 => "失败"
		);
		try {
			if(isset($state)){
				
			}else{
				$msgM = new Application_Model_DbTable_Msg();
				$msgL = $msgM->fetchRow(" `id` = {$id} ");
				$data = array(
					"state" => ($msgL["state"])?"0":"1"
				);
				if($msgM->update($data, " `id` = {$id} ")){
					$msgL = $msgM->fetchRow(" `id` = {$id} ");
					$redata["status"] = 1;
					$redata["msg"]    = "成功";
					if($msgL)
						$redata["msg"]	  = $msgL->toArray();
				}else{
					
				}				
			}
		}catch (Exception $e){
			
		}
		$this->_helper->json($redata);
	}
}

